package com.example.calendardemo.ui.main;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.calendardemo.R;
import com.example.calendardemo.adapter.MyAdapter;
import com.example.calendardemo.adapter.TimeTagListAdapter;
import com.example.calendardemo.beans.TimeTagBeans;
import com.example.calendardemo.util.ConstUtils;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

public class MainActivity extends AppCompatActivity implements
        CalendarView.OnCalendarSelectListener,
        CalendarView.OnYearChangeListener,
        View.OnClickListener {

    private LinearLayout llTabOneView, llTabTwoView;
    private TextView tvTabOne, tvTabTwo, tv_seven, tv_one, tv_two, tv_three, tv_four, tv_five, tv_six, tv_add;
    private ListView listView;
    private MyAdapter myAdapter;

    TextView mTextMonthDay;
    TextView mTextYear;
    TextView mTextLunar;
    TextView mTextCurrentDay;
    CalendarView mCalendarView;
    RelativeLayout mRelativeTool;
    FrameLayout fl_current;
    ImageView iv_clear;
    private int mCurYear;
    private int mCurMonth;
    CalendarLayout mCalendarLayout;
    TextView tvSwitchButton; //是否开启今日体验
    ListView mLvTimeTag;// 当日体验时间段列表
    private int markColor = 0xFF40c5a1;
    private String markText = "记";

    //存放每周x对应的体验日期时间段
    private Map<Integer, List<TimeTagBeans>> mWeeklyCalendarDataMap = new HashMap<>();

    private List<Calendar> mCurrentMonthCalendars = new ArrayList<>();
    private List<TextView> mWeekList = new ArrayList<>();
    private List<TimeTagBeans> seven_cycleBeans = new ArrayList<>();//周日时间段集合
    private List<TimeTagBeans> one_cycleBeans = new ArrayList<>();//周一时间段集合
    private List<TimeTagBeans> two_cycleBeans = new ArrayList<>();//周二
    private List<TimeTagBeans> three_cycleBeans = new ArrayList<>();//周三
    private List<TimeTagBeans> four_cycleBeans = new ArrayList<>();//周四
    private List<TimeTagBeans> five_cycleBeans = new ArrayList<>();//周五
    private List<TimeTagBeans> six_cycleBeans = new ArrayList<>();//周六

    private int key = 0;//默认key=0，指周日
    private List<TimeTagBeans> mTimeTagDataList = new ArrayList<>();
    private TimeTagListAdapter mTimeTagAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUI();

        setAdpter();
    }

    private void initUI() {
        tvTabOne = findViewById(R.id.tvTabOne);
        tvTabTwo = findViewById(R.id.tvTabTwo);
        llTabOneView = findViewById(R.id.llTabOneView);
        llTabTwoView = findViewById(R.id.llTabTwoView);
        tv_seven = findViewById(R.id.tv_day_seven); //周起始：周日，下标0
        tv_one = findViewById(R.id.tv_day_one);
        tv_two = findViewById(R.id.tv_day_two);
        tv_three = findViewById(R.id.tv_day_three);
        tv_four = findViewById(R.id.tv_day_four);
        tv_five = findViewById(R.id.tv_day_five);
        tv_six = findViewById(R.id.tv_day_six);

        listView = findViewById(R.id.lv);
        tv_add = findViewById(R.id.tv_add);

        //日历
        mTextMonthDay = findViewById(R.id.tv_month_day);
        mTextYear = findViewById(R.id.tv_year);
        mTextLunar = findViewById(R.id.tv_lunar);
        mRelativeTool = findViewById(R.id.rl_tool);
        mCalendarView = findViewById(R.id.calendarView);
        mTextCurrentDay = findViewById(R.id.tv_current_day);
        fl_current = findViewById(R.id.fl_current);
        mCalendarLayout = findViewById(R.id.calendarLayout);
        iv_clear = findViewById(R.id.iv_clear);
        tvSwitchButton = findViewById(R.id.tvSwitchButton);
        mLvTimeTag = findViewById(R.id.lvTimeTag);
        tvTabOne.setSelected(true);
        tv_seven.setSelected(true);
        mWeekList.add(tv_seven);
        mWeekList.add(tv_one);
        mWeekList.add(tv_two);
        mWeekList.add(tv_three);
        mWeekList.add(tv_four);
        mWeekList.add(tv_five);
        mWeekList.add(tv_six);

        setListener();
        initData();
    }

    private void setListener() {
        tvTabOne.setOnClickListener(this);
        tvTabTwo.setOnClickListener(this);

        tv_seven.setOnClickListener(this);
        tv_one.setOnClickListener(this);
        tv_two.setOnClickListener(this);
        tv_three.setOnClickListener(this);
        tv_four.setOnClickListener(this);
        tv_five.setOnClickListener(this);
        tv_six.setOnClickListener(this);

        mTextMonthDay.setOnClickListener(this);
        fl_current.setOnClickListener(this);
        mCalendarView.setOnYearChangeListener(this);
        mCalendarView.setOnCalendarSelectListener(this);
        //设置日期拦截事件，当前有效
        iv_clear.setOnClickListener(this);

        tv_add.setOnClickListener(this);
    }

    private void initData() {
        mTextYear.setText(String.valueOf(mCalendarView.getCurYear()));
        mCurYear = mCalendarView.getCurYear();
        mTextMonthDay.setText(mCalendarView.getCurMonth() + "月" + mCalendarView.getCurDay() + "日");
        mTextLunar.setText("今日");
        mTextCurrentDay.setText(String.valueOf(mCalendarView.getCurDay()));
        if (mTimeTagAdapter == null) {
            mTimeTagAdapter = new TimeTagListAdapter(this, mTimeTagDataList);
            mLvTimeTag.setAdapter(mTimeTagAdapter);
        }

        updateCalendarMarkDate();

//        Map<String, Calendar> map = new HashMap<>();
//        map.put(getSchemeCalendar(year, month, 3, markColor, markText).toString(),
//                getSchemeCalendar(year, month, 3, markColor, markText));
//        map.put(getSchemeCalendar(year, month, 6, markColor, markText).toString(),
//                getSchemeCalendar(year, month, 6, markColor, markText));
//        map.put(getSchemeCalendar(year, month, 9, markColor, markText).toString(),
//                getSchemeCalendar(year, month, 9, markColor, markText));
//        map.put(getSchemeCalendar(year, month, 13, markColor, markText).toString(),
//                getSchemeCalendar(year, month, 13, markColor, markText));
//        map.put(getSchemeCalendar(year, month, 14, markColor, markText).toString(),
//                getSchemeCalendar(year, month, 14, markColor, markText));
//        map.put(getSchemeCalendar(year, month, 15, markColor, markText).toString(),
//                getSchemeCalendar(year, month, 15, markColor, markText));
//        map.put(getSchemeCalendar(year, month, 18, markColor, markText).toString(),
//                getSchemeCalendar(year, month, 18, markColor, markText));
//        map.put(getSchemeCalendar(year, month, 25, markColor, markText).toString(),
//                getSchemeCalendar(year, month, 25, markColor, markText));
//        map.put(getSchemeCalendar(year, month, 27, markColor, markText).toString(),
//                getSchemeCalendar(year, month, 27, markColor, markText));
//        //此方法在巨大的数据量上不影响遍历性能，推荐使用
//        mCalendarView.setSchemeDate(map);
    }

    /**
     * 更新日历UI中的标记日期
     */
    private void updateCalendarMarkDate() {
//    private void updateCalendarMarkDate(String buttonType, int keyPostion) {
        try {
            mCalendarView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    setUI();
                }
            }, 2);
        } catch (Exception e) {
            Log.i("callhh", e.toString());
        }
    }

    private void setUI() {
        mCurrentMonthCalendars = mCalendarView.getCurrentMonthCalendars();//当前月份日期
        Log.i("callhh", "mCurrentMonthCalendars : " + mCalendarView.getCurrentMonthCalendars());
        int year = mCalendarView.getCurYear();
        int month = mCalendarView.getCurMonth();
        Map<String, Calendar> map = new HashMap<>();
//            List<Calendar> currentMonthCalendars = mCalendarView.getCurrentMonthCalendars();//当前月份日期
        //循环当月日期
        if (mCurrentMonthCalendars == null || mCurrentMonthCalendars.size() <= 0) return;
        for (int i = 0; i < mCurrentMonthCalendars.size(); i++) {
            int markMonth = mCurrentMonthCalendars.get(i).getMonth();
            int markYear = mCurrentMonthCalendars.get(i).getYear();
            if (markMonth != month) {
                month = markMonth;
                if (markYear != year) year = markYear;
                Log.i("callhh", "markMonth : " + markMonth);
            }
            Log.i("callhh", "month : " + month);

            int markDay = mCurrentMonthCalendars.get(i).getDay();//当前日
            int curWeek = mCurrentMonthCalendars.get(i).getWeek();//当前周
            if (mWeeklyCalendarDataMap.size() <= 0) {
                mCalendarView.clearSchemeDate();
                return;
            }
            //获取HashMap集合的key值
            Set<Integer> integers = mWeeklyCalendarDataMap.keySet();
            for (int pos : integers) {
                //判断是否是当前周x
                if (pos == curWeek) {
                    List<TimeTagBeans> timeNoteBeans = mWeeklyCalendarDataMap.get(pos);
                    //获取Hashmap里面Key对应的内容是否有数据，有数据才添加日期标记
                    if (timeNoteBeans.size() > 0) {
                        map.put(getSchemeCalendar(year, month, markDay, markColor, markText).toString(),
                                getSchemeCalendar(year, month, markDay, markColor, markText));
                        //添加标记日期，此方法在巨大的数据量上不影响遍历性能，推荐使用
                        mCalendarView.setSchemeDate(map);
                    } else {
                        //删除标记日期
                        mCalendarView.removeSchemeDate(getSchemeCalendar(year, month, markDay, markColor, markText));
                    }
                }
            }
        }
//        setSelectDateContent(key);
    }

    private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        return calendar;
    }

    @Override
    public void onCalendarOutOfRange(Calendar calendar) {

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {
        try {
            mTextLunar.setVisibility(View.VISIBLE);
            mTextYear.setVisibility(View.VISIBLE);
            mCurYear = calendar.getYear();
            mTextMonthDay.setText(calendar.getMonth() + "月" + calendar.getDay() + "日");
            mTextYear.setText(String.valueOf(mCurYear));
            mTextLunar.setText(calendar.getLunar());

            int week = calendar.getWeek();
            Log.i("callhh", "calendar.getWeek() : " + week);
            setSelectDateContent(week);
        } catch (Exception e) {
            Log.i("callhh", e.toString());
        }
    }

    @Override
    public void onYearChange(int year) {
        mTextMonthDay.setText(String.valueOf(year));
    }

    private void setSelectDateContent(int curWeek) {
        if (mWeeklyCalendarDataMap.size() <= 0) return;
        Set<Integer> integers = mWeeklyCalendarDataMap.keySet();
        //获取key值(key值存储周x) 去匹配
        for (Integer posKey : integers) {
            //判断是否是当前周x
            if (posKey == curWeek) {
                List<TimeTagBeans> timeTagBeans = mWeeklyCalendarDataMap.get(posKey);
                mTimeTagAdapter.refreshData(timeTagBeans);
                Log.i("callhh", "setSelectDateContent() timeTagBeans.size: " + timeTagBeans.size());
                return;
            } else {
                List<TimeTagBeans> timeTagBeans = new ArrayList<>();
                mTimeTagAdapter.refreshData(timeTagBeans);
            }
        }
    }


    private void setAdpter() {
        //cycleBeans = listMap.get(key);
        myAdapter = new MyAdapter(this, one_cycleBeans);
        listView.setAdapter(myAdapter);
        myAdapter.setOnDayClickListener(new MyAdapter.onDelClickListener() {
            @Override
            public void del(View v, int pos) {
                switch (key) {
                    case ConstUtils.KEY_ITEM_0:
                        one_cycleBeans.remove(pos);
                        myAdapter.refreshData(one_cycleBeans);
                        mWeeklyCalendarDataMap.put(ConstUtils.KEY_ITEM_0, one_cycleBeans);
//                        Log.i("callhh", "DEL  mWeeklyCalendarDataMap.get(0).size() : " + mWeeklyCalendarDataMap.get(0).size());

                        break;
                    case ConstUtils.KEY_ITEM_1:
                        two_cycleBeans.remove(pos);
                        myAdapter.refreshData(two_cycleBeans);
                        mWeeklyCalendarDataMap.put(ConstUtils.KEY_ITEM_1, two_cycleBeans);
                        break;
                    case ConstUtils.KEY_ITEM_2:
                        three_cycleBeans.remove(pos);
                        myAdapter.refreshData(three_cycleBeans);
                        mWeeklyCalendarDataMap.put(ConstUtils.KEY_ITEM_2, three_cycleBeans);
                        break;
                    case ConstUtils.KEY_ITEM_3:
                        four_cycleBeans.remove(pos);
                        myAdapter.refreshData(four_cycleBeans);
                        mWeeklyCalendarDataMap.put(ConstUtils.KEY_ITEM_3, four_cycleBeans);
                        break;
                    case ConstUtils.KEY_ITEM_4:
                        five_cycleBeans.remove(pos);
                        myAdapter.refreshData(five_cycleBeans);
                        mWeeklyCalendarDataMap.put(ConstUtils.KEY_ITEM_4, five_cycleBeans);
                        break;
                    case ConstUtils.KEY_ITEM_5:
                        six_cycleBeans.remove(pos);
                        myAdapter.refreshData(six_cycleBeans);
                        mWeeklyCalendarDataMap.put(ConstUtils.KEY_ITEM_5, six_cycleBeans);
                        break;
                    case ConstUtils.KEY_ITEM_6:
                        seven_cycleBeans.remove(pos);
                        myAdapter.refreshData(seven_cycleBeans);
                        mWeeklyCalendarDataMap.put(ConstUtils.KEY_ITEM_6, seven_cycleBeans);
                        break;
                }


            }
        });
    }

    /**
     * 如果没有星期栏的数据，删除HashMap 子元素
     */
    private void removeMapKep() {
        //采用迭代器遍历，不仅适用于HashMap，对其它类型的容器同样适用
        Iterator<Map.Entry<Integer, List<TimeTagBeans>>> iterator = mWeeklyCalendarDataMap.entrySet().iterator();
        for (Iterator<Map.Entry<Integer, List<TimeTagBeans>>> it = iterator; it.hasNext(); ) {
//            Map.Entry<Integer, List<TimeTagBeans>> next = it.next();
            //... todo with item
            it.remove();

        }
    }

    /**
     * 设置星期itemView选中状态
     *
     * @param position
     */
    private void setWeekSelectState(int position) {
        if (mWeekList.size() <= 0) return;
        for (int i = 0; i < mWeekList.size(); i++) {
            if (i == position) {
                mWeekList.get(position).setSelected(true);
            } else {
                mWeekList.get(i).setSelected(false);
            }
        }
    }

    /**
     * 往集合添加每日时间段对象，并更新mWeeklyCalendarDataMap和列表UI
     * key == 0-6,即周日、周一、周二、周三、周四、周五、周六
     */
    private void addDailyTimeBeanList() {
        switch (key) {
            case ConstUtils.KEY_ITEM_0:
                //周日
                addListItemAndUpdateCalendar(key, one_cycleBeans);
                break;
            case ConstUtils.KEY_ITEM_1:
                //周一
                addListItemAndUpdateCalendar(key, two_cycleBeans);
                break;
            case ConstUtils.KEY_ITEM_2:
                //周二
                addListItemAndUpdateCalendar(key, three_cycleBeans);
                break;
            case ConstUtils.KEY_ITEM_3:
                //周三
                addListItemAndUpdateCalendar(key, four_cycleBeans);
                break;
            case ConstUtils.KEY_ITEM_4:
                //周四
                addListItemAndUpdateCalendar(key, five_cycleBeans);
                break;
            case ConstUtils.KEY_ITEM_5:
                //周五
                addListItemAndUpdateCalendar(key, six_cycleBeans);
                break;
            case ConstUtils.KEY_ITEM_6:
                //周六
                addListItemAndUpdateCalendar(key, seven_cycleBeans);
                break;
        }
    }

    /**
     * 添加listItem时间段,并更新日历事件标记
     *
     * @param keyPostion   星期下标，0-6 == 周日-周六
     * @param weekBeanList 每个星期x中的时间段集合
     */
    private void addListItemAndUpdateCalendar(int keyPostion, List<TimeTagBeans> weekBeanList) {
        if (weekBeanList.size() > 0) {
            for (int i = 0; i < weekBeanList.size(); i++) {
                TimeTagBeans beans = weekBeanList.get(i);
                if (TextUtils.isEmpty(beans.getSt_time_one()) || TextUtils.isEmpty(beans.getSt_time_two())
                        || TextUtils.isEmpty(beans.getEnd_time_one()) || TextUtils.isEmpty(beans.getEnd_time_two())) {
                    Toast.makeText(this, "请先填充完第" + (i + 1) + "条内容后，再添加新内容！", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }
        weekBeanList.add(new TimeTagBeans("", "", "", ""));
        myAdapter.refreshData(weekBeanList);
        mWeeklyCalendarDataMap.put(keyPostion, weekBeanList);
//        Log.i("callhh","ADD  mWeeklyCalendarDataMap.size() : " + mWeeklyCalendarDataMap.get(0).size());

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvTabOne:
                tvTabOne.setSelected(true);
                tvTabTwo.setSelected(false);
                llTabOneView.setVisibility(View.VISIBLE);
                llTabTwoView.setVisibility(View.GONE);
                break;
            case R.id.tvTabTwo:
                tvTabOne.setSelected(false);
                tvTabTwo.setSelected(true);
                llTabOneView.setVisibility(View.GONE);
                llTabTwoView.setVisibility(View.VISIBLE);
                updateCalendarMarkDate();
                break;
            case R.id.tv_day_seven:
                key = 0;
                myAdapter.refreshData(one_cycleBeans);
                setWeekSelectState(key);
                break;
            case R.id.tv_day_one:
                key = 1;
                myAdapter.refreshData(two_cycleBeans);
                setWeekSelectState(key);
                break;
            case R.id.tv_day_two:
                key = 2;
                myAdapter.refreshData(three_cycleBeans);
                setWeekSelectState(key);
                break;
            case R.id.tv_day_three:
                key = 3;
                myAdapter.refreshData(four_cycleBeans);
                setWeekSelectState(key);
                break;
            case R.id.tv_day_four:
                key = 4;
                myAdapter.refreshData(five_cycleBeans);
                setWeekSelectState(key);
                break;
            case R.id.tv_day_five:
                key = 5;
                myAdapter.refreshData(six_cycleBeans);
                setWeekSelectState(key);
                break;
            case R.id.tv_day_six:
                key = 6;

                myAdapter.refreshData(seven_cycleBeans);
                setWeekSelectState(key);
                break;
            case R.id.tv_add:
                //添加数据
                addDailyTimeBeanList();

                break;
            case R.id.tv_month_day:
                if (!mCalendarLayout.isExpand()) {
                    mCalendarLayout.expand();
                    return;
                }
                mCalendarView.showYearSelectLayout(mCurYear);
                mTextLunar.setVisibility(View.GONE);
                mTextYear.setVisibility(View.GONE);
                mTextMonthDay.setText(String.valueOf(mCurYear));
                break;
            case R.id.fl_current:
                mCalendarView.scrollToCurrent();
                break;
            case R.id.iv_clear:
                //清楚当前标记日期
                //清楚当前标记日期
                //清楚当前标记日期
                mCalendarView.clearMultiSelect();
                break;
        }
    }


}
